<template>
    <div class="app-page-mobile">
      <!-- 顶部标题区域 -->
      <div class="header">
        <h1>{{ title }}</h1>
        <p class="description">{{ description }}</p>
      </div>

      <!-- 主要内容区域 -->
      <div class="content-container">
        <div class="content">

          <!-- 预览区域 -->
          <div class="preview-section">
            <div class="preview-container">
                <div class="preview-area" v-loading="generating">
          <!-- 空状态 -->
          <div v-if="!generatedImage && !generating" class="preview-placeholder">
            <div class="placeholder-content">
              <img :src="placeholderImage" alt="应用预览" class="placeholder-image" />
              <p class="placeholder-text">上传素材并配置参数后点击生成查看效果</p>
            </div>
          </div>
          
          <!-- 生成中状态 -->
          <div v-else-if="generating" class="processing-preview">
            <el-tag :type="processingStatus === 'exception' ? 'danger' : 'info'" class="status-tag">
              {{ getStatusText() }}
            </el-tag>
            <p class="processing-text">AI正在生成中...</p>
          </div>
          
          <!-- 生成结果 -->
          <div v-else class="result-preview">
            <div class="preview-image-container">
              <el-image 
                :src="generatedImage" 
                fit="contain"
                class="preview-image"
                :preview-src-list="[generatedImage]"
                :initial-index="0"
              ></el-image>
            </div>
            <div class="image-meta">
              <p><strong>生成时间：</strong> {{ formatDate(new Date()) }}</p>
            </div>
          </div>
        </div>
            </div>
          </div>                
          <!-- 参数配置区域 -->
          <div class="params-section">
              <el-form
              ref="paramsForm"
              :model="formData"
              label-position="top"
              class="params-form"
              v-if="paramsLoaded"
            >
              <el-form-item
                v-for="(param, key) in filteredParams"
                :key="key"
                :label="param.label"
              >
              <!-- 图像上传控件 -->
              <div v-if="param.type === 'image'" class="image-upload-block">
                <el-upload
                  class="upload-box"
                  drag
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="(file) => handleImageChange(file, key)"
                  :before-upload="beforeUpload"
                >
                  <template v-if="formData[key]">
                    <div class="image-preview-container">
                      <img :src="formData[key]" class="uploaded-image-preview" />
                      <div class="image-actions">
                        <el-button 
                          type="danger" 
                          circle 
                          size="small"
                          @click.stop="removeImage(key)"
                        >
                          <el-icon><delete /></el-icon>
                        </el-button>
                      </div>
                    </div>
                  </template>
                  <div v-else class="el-upload__text">点击或拖拽上传图片</div>
                </el-upload>
              </div>

                <!-- 颜色选择器 -->
                <ColorPicker
                  v-else-if="param.type === 'colorPicker'"
                  v-model="formData[key]"
                  :show-alpha="false"
                  :preset-colors="['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff', '#ff00ff']"
                  :disabled="false"
                  @change="(color) => handleColorChange(key, color)"
                />
                
                <!-- 文本域 -->
                <el-input
                  v-else-if="param.type === 'textarea'"
                  v-model="formData[key]"
                  type="textarea"
                  :rows="param.rows || 4"
                  :placeholder="param.placeholder"
                />
                
                <!-- 数字输入 -->
                <el-input-number
                  v-else-if="param.type === 'number'"
                  v-model="formData[key]"
                  :min="param.min"
                  :max="param.max"
                  :step="param.step || 1"
                  style="width: 100%"
                />
                
                <!-- 选择器 -->
                <el-select
                  v-else-if="param.type === 'select'"
                  v-model="formData[key]"
                  style="width: 100%"
                >
                  <el-option
                    v-for="option in param.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
                
                <!-- 文本输入 -->
                <el-input
                  v-else
                  v-model="formData[key]"
                  :placeholder="param.placeholder"
                />
              </el-form-item>
            </el-form>
          </div>



          <!-- 生成按钮 -->
          <div class="generate-button-container">
            
            <el-button
            type="primary"
            @click="generateImage"
            :loading="generating"
            :disabled="!canSubmit"
          >
            <el-icon><magic-stick /></el-icon> 生成图像
          </el-button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import api from '../api'
  import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
  import { 
    UploadFilled, 
    Download, 
    RefreshRight, 
    Delete, 
    MagicStick,
    Close,
    Warning,
    Operation,
    Upload
  } from '@element-plus/icons-vue'
  import axios from 'axios'
  import ColorPicker from './ColorPicker.vue'
  import eventBus from '../utils/eventBus'
  
  const emit = defineEmits(['generation-success'])
  
  const props = defineProps({
    title: {
      type: String,
      required: true
    },
    description: {
      type: String,
      required: true
    },
    operation_steps: {
      type: String,
      required: true
    },
    workflowParams: {
      type: Object,
      required: true
    },
    workflowId: {
      type: String,
      required: true
    }
  })
  
  const router = useRouter()
  const formData = ref({})
  const paramsLoaded = ref(false)
  const generating = ref(false)
  const generatedImage = ref('')
  const lastSeed = ref(null)
  const generationHistory = ref([])
  const paramsForm = ref(null)
  const uploadedImage = ref('')
  const processingProgress = ref(0)
  const processingStatus = ref('')
  const cancelFlag = ref(false)
  
  // 根据当前路由获取对应的预览图像
  const placeholderImage = computed(() => {
    const currentPath = router.currentRoute.value.path
    const imageMap = {
      '/hairrecolor': '/images/home/hairRecolor.png',
      '/facebeauty': '/images/home/faceBeauty.png',
      '/convert_to_anime': '/images/home/convertoAnime.png'
    }
    return imageMap[currentPath] || '/images/placeholder.png'
  })
  
  // 格式化时间的函数
  const formatTime = (timestamp) => {
    if (!timestamp) return ''

    const date = new Date(timestamp)
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return ''
    }

    const now = new Date()
    const diff = now - date

    // 如果是今天
    if (diff < 24 * 60 * 60 * 1000) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `今天 ${hours}:${minutes}`
    }

    // 如果是昨天
    if (diff < 48 * 60 * 60 * 1000) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `昨天 ${hours}:${minutes}`
    }

    // 如果是今年
    if (date.getFullYear() === now.getFullYear()) {
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${month}-${day} ${hours}:${minutes}`
    }

    // 其他情况显示完整日期
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  }

// 格式化日期
const formatDate = (date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date)
}  
  
  // 获取状态文本
  const getStatusText = () => {
    switch (processingStatus.value) {
      case 'processing':
        return '正在生成图像...'
      case 'success':
        return '生成成功'
      case 'exception':
        return '生成失败'
      default:
        return '等待中...'
    }
  }
  
  // 过滤掉图片类型的参数
  const filteredParams = computed(() => {
    const result = {}
    Object.entries(props.workflowParams).forEach(([key, param]) => {
      result[key] = param
    })
    return result
  })
  
  // 计算是否可以提交
  const canSubmit = computed(() => {
    return paramsLoaded.value
  })
  
  // 上传前钩子
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('只能上传图片文件!')
    }
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      ElMessage.error('文件大小不能超过 10MB!')
    }  
    return isImage
  }
  
  // 处理图片选择变化
  const handleImageChange = (file, key) => {
    if (file) {
      const previewUrl = URL.createObjectURL(file.raw)
      formData.value[key] = previewUrl
      formData.value[`${key}_file`] = file.raw
    }
  }
  
  // 获取图片并转换为blob URL
  const fetchAndConvertImage = async (imageUrl) => {
    try {
      const response = await api.get(imageUrl, { responseType: 'blob' })
      return URL.createObjectURL(response)
    } catch (error) {
      console.error('获取图片失败', error)
      throw error
    }
  }
  
  // 生成图像
  const generateImage = async () => {
    if (!paramsLoaded.value) {
      ElMessage.warning('请先上传图片并等待参数加载完成')
      return
    }
    
    generating.value = true
    generatedImage.value = ''
    processingStatus.value = ''
    
    // 滚动到预览区域
    const previewSection = document.querySelector('.preview-container')
    if (previewSection) {
      previewSection.scrollIntoView({ block: 'start' })
    }
    
    try {
      const formDataToSend = new FormData()
  
      Object.entries(formData.value).forEach(([key, value]) => {
        if (key.endsWith('_file')) {
          formDataToSend.append(key.replace('_file', ''), value)
        } else if (!key.endsWith('_file') && typeof value !== 'string' || !value.startsWith('blob:')) {
          formDataToSend.append(key, value)
        }
      })
  
      formDataToSend.append('workflowId', props.workflowId)
  
      const response = await api.post(
        `/queue/generate`,
        formDataToSend,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      )
      if (!response || typeof response !== 'object' || response.code !== 0 || !response.result || !response.result.taskId) {
        throw new Error(response?.msg || '生成任务创建失败')
      }
      const taskId = response.result.taskId
      await waitForTaskComplete(taskId)
  
      ElMessage.success('图像生成成功')
      
      // 触发生成成功事件，通知父组件刷新历史记录
      emit('generation-success')
      
      // 通过事件总线通知其他组件刷新历史记录
      eventBus.emit('generation-success')
    } catch (error) {
      processingStatus.value = 'exception'
      console.error('生成失败', error)
      ElMessage.error('图像生成失败: ' + (error.response?.data?.error || error.message || '未知错误'))
    } finally {
      setTimeout(() => {
        generating.value = false
      }, 500)
    }
  }
  
  // 下载图像
  const downloadImage = async (imageUrl) => {
    try {
      const response = await fetch(imageUrl)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `generated-image-${formData.value.seed || 'unknown'}.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error('下载失败', error)
      ElMessage.error('图像下载失败')
    }
  }
  
  // 中断生成
  const cancelGeneration = () => {
    cancelFlag.value = true
    ElMessage.warning('正在中断生成...')
  }
  
  // 等待任务完成
  const waitForTaskComplete = async (taskId) => {
    processingStatus.value = 'processing'
    cancelFlag.value = false
    
    while (!cancelFlag.value) {
      try {
        const response = await api.get(`/queue/checktaskstatus?taskId=${taskId}`)
        if (!response || typeof response !== 'object' || response.code !== 0 || !response.result) {
          throw new Error(response?.msg || '任务状态获取失败')
        }
        const task = response.result
        if (task.status === 'FAILED') {
          throw new Error(task.errorMsg || '任务执行失败')
        }
        if (task.status === 'COMPLETED') {
          if (task.imagePath) {
            processingStatus.value = 'success'
            const blobUrl = await fetchAndConvertImage(task.imagePath)
            if (blobUrl) {
              generatedImage.value = blobUrl
              generationHistory.value.unshift({
                imageUrl: blobUrl,
                seed: formData.value.seed,
                params: JSON.parse(JSON.stringify(formData.value)),
                timestamp: new Date()
              })
            }
            break
          } else {
            throw new Error('未找到生成的图像')
          }
        }
        await new Promise(resolve => setTimeout(resolve, 1000))
      } catch (error) {
        console.error('检查任务状态失败', error)
        processingStatus.value = 'exception'
        throw error
      }
    }
    
    if (cancelFlag.value) {
      processingStatus.value = 'exception'
      throw new Error('生成已中断')
    }
  }
  
  // 删除图片
  const removeImage = (key) => {
    if (formData.value[key] && formData.value[key].startsWith('blob:')) {
      URL.revokeObjectURL(formData.value[key])
    }
    formData.value[key] = ''
    formData.value[`${key}_file`] = null
  }
  
  // 处理颜色变化
  const handleColorChange = (key, color) => {
    console.log(`颜色已更改: ${key} = ${color}`)
    formData.value[key] = color
  }
  
  // 组件挂载时设置参数
  onMounted(async () => {
    // 设置默认值
    if (props.workflowParams) {
      Object.entries(props.workflowParams).forEach(([key, param]) => {
        formData.value[key] = param.default
      })
      paramsLoaded.value = true
    }
  })
  
  // 监听 workflowParams 变化
  watch(() => props.workflowParams, (newParams) => {
    if (newParams) {
      Object.entries(newParams).forEach(([key, param]) => {
        formData.value[key] = param.default
      })
      paramsLoaded.value = true
    }
  }, { deep: true })
  
  // 组件卸载前清理
  onBeforeUnmount(() => {
    Object.entries(formData.value).forEach(([key, value]) => {
      if (typeof value === 'string' && value.startsWith('blob:')) {
        URL.revokeObjectURL(value)
      }
    })
  })
  </script>
  
  <style scoped>
  .app-page-mobile {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 50px - 50px);
    background-color: #f5f7fa;
    overflow: hidden
  }
  
  .header {
    padding: 16px;
    background: #fff;
    border-bottom: 1px solid #e4e7ed;
    position: sticky;
    top: 0;
    z-index: 10;
  }
  
  .header h1 {
    margin: 0;
    font-size: 20px;
    color: #303133;
  }
  
  .description {
    margin: 8px 0 0;
    font-size: 14px;
    color: #606266;
  }
  
  .content-container {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    background: var(--el-bg-color-page);
    padding-bottom: 56px; /* 生成按钮容器的高度 */
  }
  
  .content {
    padding: 16px;
  }
  
  .params-section {
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    margin-bottom: 16px;
  }
  
  .params-form {
    width: 100%;
  }
  
  .params-form :deep(.el-form-item) {
    margin-bottom: 20px;
  }
  
  .params-form :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    padding-bottom: 8px;
  }
  
  .image-upload-block {
    width: 100%;
  }
  
  .upload-box {
    width: 100%;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
  }
  
  .upload-box:hover {
    border-color: #409eff;
  }
  
  .image-preview-container {
    position: relative;
    width: 100%;
    padding-top: 100%; /* 1:1 宽高比 */
  }
  
  .uploaded-image-preview {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .image-actions {
    position: absolute;
    top: 8px;
    right: 8px;
    z-index: 1;
  }
  
  .params-form :deep(.el-color-picker) {
    width: 100%;
  }
  
  .params-form :deep(.el-color-picker__trigger) {
    width: 100%;
    height: 40px;
    padding: 4px;
  }
  
  .params-form :deep(.el-textarea__inner) {
    min-height: 80px;
    font-size: 14px;
    line-height: 1.5;
  }
  
  .params-form :deep(.el-slider) {
    margin: 8px 0;
  }
  
  .params-form :deep(.el-slider__runway) {
    height: 4px;
  }
  
  .params-form :deep(.el-slider__bar) {
    height: 4px;
    background-color: #409eff;
  }
  
  .params-form :deep(.el-slider__button) {
    width: 16px;
    height: 16px;
    border: 2px solid #409eff;
  }
  
  .params-form :deep(.el-select) {
    width: 100%;
  }
  
  .params-form :deep(.el-input__wrapper) {
    padding: 0 12px;
  }
  
  .params-form :deep(.el-input__inner) {
    height: 40px;
    font-size: 14px;
  }
  
  .preview-section {
    padding: 10px 0px;
    background-color: #f5f7fa;
  }
  
  .preview-container {
    width: 100%;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    cursor: pointer;
  }
  
  .upload-placeholder .el-icon {
    font-size: 32px;
    margin-bottom: 8px;
  }
  
  .preview-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 0px;
    width: 100%;
  }
  
  .placeholder-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    width: 100%;
    height: 100%;
  }
  
  .placeholder-image {
    width: calc(100% - 10px);
    height: calc(100% - 10px);
    object-fit: cover;
    border-radius: 10px;
    margin-bottom: 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  .placeholder-text {
    color: #606266;
    font-size: 14px;
    margin: 0;
    line-height: 1.5;
  }
  
  .generate-button-container {
    position: fixed;
    bottom: 50px;
    left: 0;
    right: 0;
    padding: 4px 12px;
    background: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-light);
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .generate-button {
    width: 100%;
    max-width: 320px;
    height: 40px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 20px;
    background: var(--el-color-primary);
    color: white;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }
  
  .preview-dialog-content {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
  
  .preview-dialog-image {
    max-width: 100%;
    max-height: 70vh;
  }
  
  .preview-dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  /* 移动端适配 */
  @media screen and (max-width: 768px) {
    .header {
      padding: 12px;
    }
  
    .header h1 {
      font-size: 18px;
    }
  
    .description {
      font-size: 13px;
    }
  
    .content {
      padding: 12px;
    }
  }
  
  /* 暗色主题适配 */
  @media (prefers-color-scheme: dark) {
    .app-page-mobile {
      background-color: #1a1a1a;
    }
  
    .header {
      background: #1a1a1a;
      border-bottom-color: #333;
    }
  
    .header h1 {
      color: #e0e0e0;
    }
  
    .description {
      color: #909399;
    }
  }

  /* 图片容器 */
.preview-image-container {
  flex: 1;
  min-height: 400px;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: 600px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 0;
}

  /* 暗色主题适配 */
  @media (prefers-color-scheme: dark) {
    .generate-button-container {
      background: var(--el-bg-color-overlay);
      border-top-color: var(--el-border-color-darker);
      box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.15);
    }
  }

  /* 移动端适配 */
  @media screen and (max-width: 768px) {
    .preview-dialog :deep(.el-dialog__header) {
      padding: 10px 12px;
    }

    .preview-dialog :deep(.el-dialog__footer) {
      padding: 10px 12px;
    }

    .preview-dialog-footer {
      gap: 6px;
    }
  }
  </style> 